package io.xccit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Xccit
 * @Date 2023-02-25
 * @Description
 */
@Controller
public class ScopeController {
    @RequestMapping("req")
    public String reqScope(HttpServletRequest request){
        request.setAttribute("reqUserName","原生Servlet设置UserName!");
        return "success";
    }

    /**
     * ModelAndView:
     *  Model:分享信息的容器
     *  View:视图信息
     * @return 分享的信息及要跳转的视图信息
     */
    @RequestMapping("mav")
    public ModelAndView mavScope(){
        //新建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        //在对象内设置共享到域对象的对象信息
        modelAndView.addObject("mavUserName","使用ModelAndView设置UserName!");
        //设置要跳转的逻辑视图名
        modelAndView.setViewName("success");
        return modelAndView;
    }
    @RequestMapping("model")
    public String modelScope(Model model){
        System.out.println("modelType:"+model.getClass().getName());
        model.addAttribute("modelUserName","使用Model设置的UserName!");
        return "success";
    }
    @RequestMapping("modelmap")
    public String modelMapScope(ModelMap modelMap){
        System.out.println("modelMapType:"+modelMap.getClass().getName());
        modelMap.addAttribute("modelMapUserName","使用ModelMap设置的UserName!");
        return "success";
    }
    @RequestMapping("map")
    public String mapScope(Map<String,Object> map){
        System.out.println("mapType:"+map.getClass().getName());
        map.put("mapUserName","使用Map设置的UserName!");
        return "success";
    }
    @RequestMapping("session")
    public String sessionScope(HttpSession session){
        session.setAttribute("sessionUserName","Hello Session!");
        return "success";
    }
    @RequestMapping("application")
    public String appScope(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("appUserName","Hello Application!");
        return "success";
    }
}
